package widget;

/* 
 * Author: rendy.jr
 * Date: Jun 10, 2011
 * 6.005 Elements of Software Construction
 * Rendy Bambang Junior
 * rendy.jr@gmail.com
 * 
 * Weather class responsible for:
 * - fetch current condition based on zipcode
 * - fetch current temperature based on zipcode
 * 
 */

import java.io.IOException;
import java.net.MalformedURLException;

import string.Match;

import browser.Browser;
import browser.Page;

public class Weather extends Page{
	//weather attributes
	private String condition;
	private String yweather;
	private int temperature;
	
	//create weather object using zipcode
	public Weather(String zipcode) throws MalformedURLException, IOException{
		super("http://weather.yahooapis.com/forecastrss?p="+zipcode);
		yweather = Match.between(this.getContent(),"<yweather:condition", "/>"); 
		condition = Match.between(yweather,"text=\"", "\"");
		temperature = Integer.parseInt(Match.between(yweather, "temp=\"", "\""));
	}
	
	//get weather condition
	public String getCondition(){
		return condition;
	}
	
	//get weather temperature
	public int getTemperature(){
		return temperature;
	}
	
	//download and get page
	@Override 
	protected void download() throws IOException {
		Page p = getPageFromCache(url.toString()); 
		if ((p != null)&&(p instanceof Weather)){ 
			this.content = p.getContent();
			this.condition = ((Weather)p).getCondition();
			this.condition = ((Weather)p).getCondition();
		}
		else{
			this.content = Browser.fetch(url.toString());
			String yweather = Match.between(this.getContent(), 
					"<yweather:condition", "/>"); 
			this.condition = Match.between(yweather,"text=\"", "\""); 
			this.temperature = Integer.parseInt(Match.between(content,"temp=\"", "\""));
			putPageInCache(this); 
		}
	}
}
